package com.graduation.service;

import com.graduation.dao.FileUploadDao;
import com.graduation.entity.Business;
import com.graduation.entity.User;
import com.graduation.exception.FileAlreadyExitsException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/*
 *@Author:君上
 *@Date 2022/3/14 16:27
 *@Content:
 */
@Service
public class FileUpServiceImpl implements FileUpService {

    @Resource
    private FileUploadDao fileUploadDao;

    //文件上传地址为resource文件下
    private static   String uploadDir;

    /**
     * 文件保存位置
     */
    static {
        // 项目路径
        File path = null;
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath());
            if (!path.exists())
                path = new File("upload");
            // 绝对路径=项目路径+自定义路径
            File upload = new File(path.getAbsolutePath(), "static/upload/");
            if (!upload.exists()){
                upload.mkdirs();
            }
            uploadDir = upload.getAbsolutePath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 图片上传和表内同步更新
     * @param file
     * @param request
     * @return
     */
    @Transactional
    @Override
    public Map<String, String> insertPaper(@RequestParam("file")MultipartFile file, HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        String newName = null;
        //获取文件名
        String uploadFileName = file.getOriginalFilename();
        //判定文件名如果为空则是用户没有上传图片
        newName = makePictureName(uploadFileName);
        //上传路径保存设置
        //如果路径不存在，创建一个
        File realPath = new File(uploadDir);
        if (!realPath.exists()) {
            realPath.mkdir();
        }
        InputStream is = null; //文件输入流
        OutputStream os = null;
        try {
            is = file.getInputStream();
            os = new FileOutputStream(new File(uploadDir, newName)); //文件输出流
            //读取写出
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //拿到email唯一值
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        //查询id
        Integer shopName = fileUploadDao.queryShopName(user.getEmail());
        Integer result = 0;
        try {
            result = fileUploadDao.insertGoodsInfo(newName, String.valueOf(shopName));
        } catch (FileAlreadyExitsException e) {
            e.printStackTrace();
        }
        //上传成功之后访问地址
        //http://localhost:8080/store/upload/1648093617278-apple.jpeg
        map.put("result", result + "");
        map.put("filePath","upload/"+newName);
        map.put("fileName", newName);
        map.put("shopName", String.valueOf(shopName));
        return map;
    }

    /**
     * 为上传的图片重新命名
     *
     * @param beforeName
     * @return
     */
    public String makePictureName(String beforeName) {
        if ("".equals(beforeName)) {
            return "";
        }
        long currenTime = System.currentTimeMillis();
        String str = String.valueOf(currenTime);
        return str + "-" + beforeName;
    }
}
